package com.woniu.product.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniu.exception.LXLGException;
import com.woniu.product.common.ProductResultCode;
import com.woniu.product.infra.model.Category;
import com.woniu.product.infra.mapper.CategoryMapper;
import com.woniu.product.service.CategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.product.service.dto.CategoryDto;
import com.woniu.product.service.form.AddCategoryForm;
import com.woniu.result.Result;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 商品类别 服务实现类
 * </p>
 *
 * @author Lucas
 * @since 2022-11-26
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    @Resource
    private StringRedisTemplate srt;
    ObjectMapper om=new ObjectMapper();

    @Override
    public Result addCategory(AddCategoryForm addCategoryForm) {
        Category parentId = getOne(new QueryWrapper<Category>().eq("category_id", addCategoryForm.getParentId()));
            if(addCategoryForm.getParentId()!=-1&&parentId == null){
                throw new LXLGException(ProductResultCode.CATEGORY_PARENT_NOT_FOUND);
            }
        Category category = BeanUtil.copyProperties(addCategoryForm, Category.class);
            category.setCategoryState("NARMAL");
        save(category);
        return Result.getInstance().setMsg("添加类别成功").setCode(200);
    }

    @Override
    public Result deleteCategory(Integer categoryId) {
        Category categoryDb = getById(categoryId);
        categoryDb.setCategoryState("DELETE");
       updateById(categoryDb);
        return Result.getInstance().setMsg("删除成功");
    }

    /**
     * 类别查询，先查数redis，redis没有的情况下查询数据库
     * @return
     */
    @Override
    public List<CategoryDto> selCategory() throws JsonProcessingException {
        String categorys = srt.opsForValue().get("lxlg:Category");
        List<CategoryDto> categoryDtos = new ArrayList<>();
        if(categorys==null||categorys.trim().equals("")){
            categoryDtos=this.selCategoryDb();
            srt.opsForValue().set("lxlg:Category",om.writeValueAsString(categoryDtos));
            srt.expire("lxlg:Category",1, TimeUnit.HOURS);
        }else{
            categoryDtos=om.readValue(categorys, new TypeReference<List<CategoryDto>>() {});
        }

        return categoryDtos;
    }

    /**
     * 数据库查询类别列表
     * @return
     */
    public List<CategoryDto> selCategoryDb() {
        System.out.println("111");
        List<Category> categoryList = list(new QueryWrapper<Category>().eq("category_state", "NARMAL"));
        List<CategoryDto> categoryDtoList = BeanUtil.copyToList(categoryList, CategoryDto.class);
        List<CategoryDto> categoryDtos = new ArrayList<>();
        HashMap<Integer, CategoryDto> map = new HashMap<>();
        for (CategoryDto categoryDto : categoryDtoList) {
            if(categoryDto.getParentId()<0){
                categoryDtos.add(categoryDto);
            }
            map.put(categoryDto.getCategoryId(),categoryDto);
        }
        //组装下级目录
        for (CategoryDto categoryDto : categoryDtoList) {
            CategoryDto parent = map.get(categoryDto.getParentId());
            if(parent==null) continue;
            if(parent.getCategoryInfoList()==null){
                parent.setCategoryInfoList(new ArrayList<>());
            }
            parent.getCategoryInfoList().add(categoryDto);
        }



        return categoryDtos;
    }





}
